package com.simen.downloader.sample;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.simen.downloader.Downloader;
import com.simen.downloader.listener.DownloadListener;
import com.simen.downloader.model.Filer;
import com.simen.downloader.model.LocalFile;
import com.simen.downloader.util.AppLog;

import java.util.ArrayList;
import java.util.List;

public class WorkListActivity extends ListActivity {

    private UrlAdapter adapter = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        List<String> urls = new ArrayList<>();
        urls.add("http://api.allfree.cc/attach/apk/201507/package_1437993377.apk");
        urls.add("http://api.allfree.cc/attach/apk/201604/package_1460610930.apk");
        urls.add("http://api.allfree.cc/attach/apk/201604/package_1460601576.apk");
        urls.add("http://api.allfree.cc/attach/apk/201604/package_1460340831.apk");
        urls.add("http://api.allfree.cc/attach/apk/201604/package_1460014218.apk");
        urls.add("http://api.allfree.cc/attach/apk/201603/package_1459411617.apk");
        urls.add("http://dwz.cn/3cmutb");
        urls.add("http://dlsw.baidu.com/sw-search-sp/soft/9d/14744/ChromeStandalone_50.0.2661.87_Setup.1461306176.exe");
        urls.add("http://api.allfree.cc/attach/apk/201604/package_1461578269.apk");
        adapter = new UrlAdapter(this, urls, getListView());
        Downloader.getInstance().register(adapter);
        setListAdapter(adapter);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.startall) {
//            Downloader.getInstance().resumeAll(this, adapter);
        } else if (item.getItemId() == R.id.stopall) {
            Downloader.getInstance().pauseAll();
        } else if (item.getItemId() == R.id.clearall) {
            Downloader.getInstance().clearAllWork(this, true);
        }
        return true;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.workmenu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private static class UrlAdapter extends BaseAdapter implements DownloadListener {
        private List<String> urls;
        private final ListView listView;
        private final Context mContext;

        public UrlAdapter(Context context, List<String> urls, ListView listView) {
            this.mContext = context;
            this.urls = urls;
            this.listView = listView;
        }

        @Override
        public int getCount() {
            return urls.size();
        }

        @Override
        public Object getItem(int position) {
            return urls.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = LayoutInflater.from(mContext).inflate(R.layout
                        .activity_downloadtest, null);
                holder = new ViewHolder();
                holder.pause = (Button) convertView.findViewById(R.id.button2);
                holder.resume = (Button) convertView.findViewById(R.id.button3);
                holder.stop = (Button) convertView.findViewById(R.id.button4);
                holder.clear = (Button) convertView.findViewById(R.id.button5);
                holder.progressBar = (ProgressBar) convertView.findViewById(R.id.progressBar);
                holder.open = (Button) convertView.findViewById(R.id.button6);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            String url = urls.get(position);
            holder.pause.setOnClickListener(new MyOnClickListener(this, url));
            holder.resume.setOnClickListener(new MyOnClickListener(this, url));
            holder.stop.setOnClickListener(new MyOnClickListener(this, url));
            holder.clear.setOnClickListener(new MyOnClickListener(this, url));
            holder.open.setOnClickListener(new MyOnClickListener(this, url));

            Filer filer = Downloader.getInstance().getWork(url);
            if (filer == null) {
                holder.progressBar.setProgress(0);
            } else {
                holder.progressBar.setProgress(filer.getProgress());
            }
            return convertView;
        }

        @Override
        public void onProgress(String key, int progress) {
            if (progress == 100) {
                AppLog.dLog("key onProgress " + Uri.parse(key).getLastPathSegment() + " " + progress);
            }
            if (urls.isEmpty()) {
                return;
            }
            int index = urls.indexOf(key);
            if (index != -1) {
                ProgressBar progressBar = (ProgressBar) listView.getChildAt(index).findViewById(R.id.progressBar);
                progressBar.setProgress(progress);
            }
        }

        @Override
        public void onComplete(String key, LocalFile localFile) {
            AppLog.dLog("key onComplete " + Uri.parse(key).getLastPathSegment());
        }

        @Override
        public void Exception(String key, Exception e) {

        }

        @Override
        public void onPause(String key) {
            AppLog.dLog("key onPause " + Uri.parse(key).getLastPathSegment());

        }

        @Override
        public void onResume(String key) {
            AppLog.dLog("key onResume " + Uri.parse(key).getLastPathSegment());
        }

        class ViewHolder {
            Button pause, resume, stop, clear, open;
            ProgressBar progressBar;
        }

        private static class MyOnClickListener implements View.OnClickListener {
            private String url;
            private final DownloadListener downloadListener;

            public MyOnClickListener(DownloadListener downloadListener, String url) {
                this.downloadListener = downloadListener;
                this.url = url;
            }

            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.button2:
                        AppLog.dLog("pause buttton is pressed ");
                        Downloader.getInstance().pauseWork(v.getContext(), url);
                        break;
                    case R.id.button3:
                        AppLog.dLog("resume buttton is pressed ");
                        Downloader.getInstance().resumeWork(v.getContext(), url, downloadListener);
                        break;
                    case R.id.button5:
                        AppLog.dLog("clear buttton is pressed ");
                        //清除
                        Downloader.getInstance().clearWork(v.getContext(), url, true);
                    case R.id.button4:
                        AppLog.dLog("query buttton is pressed ");
                        //查询
                        Filer filer = Downloader.getInstance().getWork(url);
                        View parent = (View) v.getParent().getParent();
                        ProgressBar progressBar = (ProgressBar) parent.findViewById(R.id.progressBar);
                        if (filer == null) {
                            progressBar.setProgress(0);
                        } else {
                            progressBar.setProgress(filer.getProgress());
                        }
                        break;
                    case R.id.button6:
                        AppLog.dLog("open buttton is pressed ");
                        //打开
                        filer = Downloader.getInstance().getWork(url);
                        if (filer == null || filer.getLocalPath() == null) {
                            Toast.makeText(v.getContext(), "无法打开下载文件", Toast.LENGTH_SHORT)
                                    .show();
                        } else {
                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            intent.setData(Uri.parse(filer.getLocalPath()));
                            if (intent.resolveActivity(v.getContext().getPackageManager()) != null) {
                                v.getContext().startActivity(intent);
                            } else {
                                Toast.makeText(v.getContext(), "没找到打开此文件的应用", Toast
                                        .LENGTH_SHORT).show();
                            }
                        }
                        break;
                    default:
                        AppLog.dLog("unknown buttton is pressed ");
                        break;
                }
            }
        }
    }
}
